package com.jqbd.advice;

import com.jqbd.annotation.Log;
import com.jqbd.mapper.AdminLogMapper;
import com.jqbd.pojo.Admin;
import com.jqbd.pojo.AdminLog;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

/**
 * @Author: LHY
 * @Date: 2022/11/12 16:41
 *
 * 通知类
 */
@Component
@Aspect
public class AdminAdvice {

    @Autowired
    private AdminLogMapper adminLogMapper;

    @AfterReturning("@annotation(com.jqbd.annotation.Log)")
    public void writeLog(JoinPoint joinPoint){

        // 获取当前方法的签名对象
        MethodSignature methodSignature = (MethodSignature)joinPoint.getSignature();

        // 获取当前方法
        Method method = methodSignature.getMethod();

        // 获取 @Log 注解对象
        Log log = method.getAnnotation(Log.class);

        // 获取 @Log 注解的内容
        String value = log.value();

        /**
         * 获取 ServletRequestAttributes 对象
         * 获取 ServletRequest 对象
         * 获取 Session 对象
         * 获取当前登陆的管理员的 id 和 name
         */
//        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
//        HttpServletRequest request = servletRequestAttributes.getRequest();
//        HttpSession session = request.getSession();
//
//        Admin admin = (Admin)session.getAttribute("admin");

        // 封装日志对象
        AdminLog adminLog = new AdminLog();
//        adminLog.setAdminId(admin.getAdminId());
//        adminLog.setAdminName(admin.getAdminName());
        adminLog.setInfo(value);

        // 插入数据库
        adminLogMapper.insert(adminLog);

    }

}